package com.xu.sso.db.service.impl;

import com.xu.sso.db.dao.UserExMapper;
import com.xu.sso.db.model.base.User;
import com.xu.sso.db.model.base.UserExample;
import com.xu.sso.db.service.UserDBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserDBServiceImpl implements UserDBService {

    @Autowired
    private UserExMapper userExMapper;

    @Override
    public User findUserByUsername(String username) {
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<User> users = userExMapper.selectByExample(example);
        if (null != users && users.size() > 0) {
            return users.get(0);
        }
        return null;
    }

    @Override
    public List<User> findAllUsers() {
        return userExMapper.selectByExample(new UserExample());
    }

    @Override
    public List<User> findUsersByLikeUsername(String username) {
        UserExample example = new UserExample();
        example.createCriteria().andUsernameLike("%" + username + "%");
        return userExMapper.selectByExample(example);
    }

    @Override
    public List<User> findUsersByListIn(List<String> usernames) {
        UserExample example = new UserExample();
        example.createCriteria().andUsernameIn(usernames);
        return userExMapper.selectByExample(example);
    }

    @Override
    public List<User> findAppUsers(String appId) {
        return userExMapper.selectUsersByApp(appId);
    }

    @Override
    public List<User> findNotAppUsers(String appId) {
        return userExMapper.selectUsersNotInApp(appId);
    }

    @Override
    public int createUser(User user) {
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        return userExMapper.insertSelective(user);
    }

    @Override
    public int updatePassword(String username, String password) {
        User user = new User();
        user.setPassword(password);
        user.setUpdateTime(new Date());
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(username);
        return userExMapper.updateByExampleSelective(user, example);
    }

    @Override
    public int updateUserWithoutPwd(User user) {
        user.setUpdateTime(new Date());
        user.setPassword(null);
        if (-1 == user.getDepId()) {
            user.setDepName("");
        }
        return userExMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public int deleteUser(String username) {
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(username);
        return userExMapper.deleteByExample(example);
    }
}
